package xcmg.device.infra;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.log.LogHelper;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * Created by john on 2017/4/12.
 */

@ControllerAdvice
public class ExceptionAdvice {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ActionResult processExcption(NativeWebRequest request, Exception e) {
        logger.error("WMS系统发生异常", e);
        ErrorCode code = ErrorCode.UnExceptedError;
        LogHelper.fatal(code.getDesc(), e);
        Exception cause = null == e.getCause() ? e : (Exception) e.getCause();
        String causeMessage = cause.getMessage();
        return new ActionResult<>(code.getCode(), causeMessage);
    }


    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ActionResult processIllegalArumentExcption(NativeWebRequest request, IllegalArgumentException e) {
        logger.error("WMS系统发生异常", e);
        ErrorCode code = ErrorCode.IllegalArument;

        return new ActionResult(code.getCode(), code.getDesc(), null);
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseBody
    public ActionResult processSQLIntegrityConstraintViolationException(NativeWebRequest request, IllegalArgumentException e) {

        logger.error("WMS系统发生异常", e);
        ErrorCode code = ErrorCode.SQLIntegrityConstraintViolation;
        return new ActionResult(code.getCode(), code.getDesc(), null);
    }


    /**
     * @Des 全局的sql异常捕捉
     * @Date 2021/4/25 14:34
     * @Author wangzhaoyu
     * @Param [exception]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public ActionResult processSqlException(DataAccessException exception) {
        logger.error("======================================sql异常========================", exception);
        ErrorCode code = ErrorCode.SqlSyntaxError;
        return new ActionResult(code.getCode(), "操作失败");
    }
}
